<?php
/**
 * alltosun.com qq授权 index.php
 * ============================================================================
 * 版权所有 (C) 2009-2011 北京互动阳光科技有限公司，并保留所有权利。
 * 网站地址: http://www.alltosun.com
 * ----------------------------------------------------------------------------
 * 许可声明：这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
 * ============================================================================
 * $Author: 张元昊 (zhangyh@alltosun.com) $
*/

class Action{
	private $appid;
    private $appkey;
    private $callback; // 回调地址
    private $password;
    private $hash;

    function __construct()
    {
        $openapi = Config::get('openapi');
        $this->appid = $openapi['webweixin'][0];
        $this->appkey = $openapi['webweixin'][1];
        $this->callback = $openapi['webweixin'][2];
        $this->hash = user_helper::random_hash(6);
        //echo $this->appid;
    }

    function __call($action = '', $param = array())
    {
    	$isBind = Request::Get('bind', '0');
    	if(user_helper::get_user_id() && !$isBind) {
            return array('您已经登录过了。', 'error', AnUrl('user/setting'));
        }
        $login_url = "https://open.weixin.qq.com/connect/qrconnect?appid=".$this->appid. "&redirect_uri=" . urlencode($this->callback) . "&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect";
        if($isBind) {
            $_SESSION['bind'] = $isBind;
            if(!user_helper::get_user_id()) {
                return array('您需要先登录才可以绑定第三方帐号。', 'error', AnUrl('user/login'));
            }
        } else {
            $_SESSION['bind'] = 0;
        }
        if(!isset($_SESSION['login_callback'])) {
            $_SESSION['login_callback'] = user_helper::get_jump_url($rfUrl);
        }
        Response::redirect($login_url);
    }
    function callback() {
    	$code = Request::Get('code', '');
    	if (isset($code) && !empty($code)) {
    		//获取用户token
    		$token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->appid."&secret=".$this->appkey."&code=".$code."&grant_type=authorization_code";
    		$str  = curl_request($token_url, 'get');
    		$user = json_decode($str, true);
    		
    		//获取用户信息
    		$info_url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$user['access_token']."&openid=".$user['openid'];
    		$str_info  = curl_request($info_url, 'get');
    		$user_info = json_decode($str_info, true);
            $user_info['avatar'] = $this->get_big_avatar_url($user_info['headimgurl']);
            $user_info['user_name'] = $user_info['nickname'];
			$connect_info = _uri('connect_weixin', array('unionid'=>$user_info['unionid']));
			if (!$connect_info) {
				$info = array(
						'unionid'                =>    $user_info['unionid'],
                        'connect_open_id'        =>    $user['openid'],
                        'connect_site_id'        =>    6,
                        'connect_nick_name'      =>    $user_info['nickname'],
                        'scope'                  =>    'snsapi_userinfo',
                        'access_token'   =>    $user['access_token'],
                        'refresh_token'  =>    $user['refresh_token'],
                        'expires_time'   =>    $user['expires_in']+time()
                );

                if($_SESSION['bind']) {
                    if(!user_helper::get_user_id()) {
                        return array('对不起，您还未登录！', 'error', user_helper::get_jump_url());
                    }
                    $info['user_id'] = user_helper::get_user_id();
                    $connect_id = _model('connect_weixin')->create($info);
                    if($connect_id) {
                        unset($_SESSION['bind']);
                        return array('绑定成功！', 'success', AnUrl('user/setting/account_bind'));
                    }
                }

                $connect_id = _model('connect_weixin')->create($info);
                $_SESSION['associatedConnectInfo']['id'] = $connect_id;
                $_SESSION['associatedConnectInfo']['type'] = 'weixin';
                $_SESSION['associatedConnectInfo']['user_info'] = $user_info;
                Response::redirect(AnUrl('openapi/choose_bind'));
    		} else {
    			$connect_update_info = array(
                        'connect_nick_name'      =>    $user_info['nickname'],
                        'scope'                  =>    'snsapi_userinfo',
                        'access_token'   =>    $user['access_token'],
                        'refresh_token'  =>    $user['refresh_token'],
                        'expires_time'   =>    $user['expires_in']+time()
                );
                _model('connect_weixin')->update($connect_info['id'], $connect_update_info);
                if(!$connect_info['user_id']) {
                    if($_SESSION['bind']) {
                        if(!user_helper::get_user_id()) {
                            return array('对不起，您还未登录！', 'error', user_helper::get_jump_url());
                        }
                        $affected = _model('connect_weixin')->update($connect_info['id'], array('user_id' => user_helper::get_user_id()));
                        if($affected) {
                            unset($_SESSION['bind']);
                            return array('绑定成功！', 'success', AnUrl('user/setting/account_bind'));
                        }
                    }
                    $_SESSION['associatedConnectInfo']['id'] = $connect_info['id'];
                    $_SESSION['associatedConnectInfo']['type'] = 'weixin';
                    $_SESSION['associatedConnectInfo']['user_info'] = $user_info;
                    Response::redirect(AnUrl('openapi/choose_bind'));
                } else {
                    if($_SESSION['bind']) {
                        unset($_SESSION['bind']);
                        return array('此微信帐号已经被其他帐号绑定过了', 'error', AnUrl('user/setting/account_bind'));
                    }
                    $this->user_id = $connect_info['user_id'];
                    $db_user_info = _uri('user', $this->user_id);
                    $info = array(
                            'nickname'         =>    $user_info['nickname'],
                            'nickname_base64'  =>    base64_encode($user_info['nickname']),
                            'user_from'        =>     'weixin',
                            'last_login_time'  =>    date('Y-m-d H:i:s', time())
                    );
                    if(empty($db_user_info['nickname'])) {
                        $info['nickname'] = $user_info['nickname'];
                    }
                    if(empty($db_user_info['avatar'])) {
                        $info['avatar'] = $this->get_big_avatar_url($user_info['headimgurl']);
                    }
                    _model('user')->update(array('id' => $connect_info['user_id']), $info);
                    $return_info = $this->user_login($connect_info['user_id']);
                    if($return_info['info'] != 'error') {
                        echo $return_info;
                    } else {
                        return array('微信登录失败，请重试！', 'error', AnUrl('user/login'));
                    }
                }
    		}
    	} else {
    		return array('获取用户信息失败，请重试！', 'error', AnUrl('user/login'));
    	}
    	
    }
    private function user_login($user_id)
    {
        // 本站登录，写入session
        $user_info = _uri('user', $user_id);
        user_helper::session_update($user_info, 'weixin');

        //同步登录ucenter
        $callback = $_SESSION['login_callback'];
        $return_info = user_helper::uc_login($user_info['uc_id'], '', $callback,0,1);
        return $return_info;
    }

    /**
     * 获取大头像
     */
    private function get_big_avatar_url($url)
    {
        if(!$url) {
            return '';
        }

        $url = preg_replace('/\/\d+$/', '/0', $url);

        return $url;
    }
}